package chaoyue.study.controller;

import chaoyue.study.bean.Depart;
import chaoyue.study.fallback.NacosDepartControllerFallback;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 通过nacos进行服务调用
 */
@Slf4j
@RestController
@RequestMapping("depart/nacos")
public class NacosDepartController {
    @Autowired
    private RestTemplate template;

    private static final String SERVICE_PROVIDER = "http://depart-provider/depart/";

    @PostMapping("save")
    public void saveHandle(@RequestBody Depart depart) {
        template.postForObject(SERVICE_PROVIDER + "save", depart, Void.class);
    }

    @DeleteMapping("del/{id}")
    public void deleteHandle(@PathVariable("id") Integer id) {
        template.delete(SERVICE_PROVIDER + "delete/" + id);
    }

    @PostMapping("update")
    public void updateHandle(@RequestBody Depart depart) {
        template.put(SERVICE_PROVIDER + "update", depart, Void.class);
    }

    @SentinelResource(value = "depart-get", fallback = "getHandleFallback") // 单个设置降级方法 value表示资源名称（非必须 不设置会自动生成）
    @GetMapping("get/{id}")
    public Depart getHandle(@PathVariable("id") Integer id) {
        return template.getForObject(SERVICE_PROVIDER + "get/" + id, Depart.class);
    }

    public Depart getHandleFallback(Integer id, Throwable t) {
        return new Depart(id, "方法降级 " + t);
    }

    // 使用降级类来统一管理降级方法
    @SentinelResource(value = "depart-list", fallback = "listHandleFallback", fallbackClass = NacosDepartControllerFallback.class)
    @GetMapping("list")
    public List<Depart> listHandle() {
        return template.getForObject(SERVICE_PROVIDER + "list", List.class);
    }

}
